#define _CRT_SECURE_NO_WARNINGS 1

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* transform(vector<int>& nums, int left, int right)
    {
        if (left > right) return nullptr;
        int mid = (right - left) / 2 + left;
        TreeNode* l = transform(nums, left, mid - 1);
        TreeNode* r = transform(nums, mid + 1, right);
        TreeNode* root = new TreeNode(nums[mid], l, r);
        return root;
    }
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        int n = nums.size();
        return transform(nums, 0, n - 1);
    }
};